<?php

namespace app\api\controller\v1;

use app\common\controller\ApiCommon;
use app\common\model\User;

class Users extends ApiCommon
{
    protected  $modelName = "User";
    public function index()
    {
        $this->checkPermission(0);
        $filter = json_decode($this->request->param('filter', "[]"));
        $filter[] = ['level', '>', 0];
        return parent::_index($filter);
    }

    public function enable()
    {
        $this->checkPermission(0);
        $request = $this->request;
        if (!($userName = $request->param('user_name'))) {
            return json_response([], STATUS_INVALD_PARAM, "必须传入用户名");
        }
        if (!($status = $request->param('status'))) {
            return json_response([], STATUS_INVALD_PARAM, "必须传入status参数");
        }
        $user = User::get($userName);
        if (!$user) {
            return json_response([], STATUS_NOT_FOUND, "没有找到指定的用户");
        }
        $user->status = $status;
        $user->save();
        return json_response([]);
    }

    public function save()
    {
        $this->checkPermission(0);
        $level = $this->request->param('level');
        if ($level <= 0) {
            return  json_response([], STATUS_FORBIDDEN, '不允许创建权限大于等于超级管理员的账号');
        }
        return parent::_save();
    }

    public function update($id){
        $this->checkPermission(0);
        $level = $this->request->param('level');
        if ($level <= 0) {
            return json_response([], STATUS_FORBIDDEN, '不允许赋予大于等于超级管理员的权限');
        }
        return parent::_update($id);
    }

    /**
     * 重置账号密码
     *
     * @return void
     */
    public function ResetPassword()
    {
        $this->checkPermission(0);
        $request = $this->request;
        if (!($userName = $request->param('user_name'))) {
            return json_response([], STATUS_INVALD_PARAM, "必须传入用户名");
        }
        $userModel = $this->_getModel();
        $newPassword = $userModel->resetPassword($userName);

        if ($newPassword) {
            return json_response([$newPassword]);
        } else {
            return json_response([], STATUS_FAIL, $userModel->getError());
        }
    }

    /**
     * 修改密码
     *
     * @return void
     */
    public function changePassword()
    {
        $request = $this->request;
        $userModel = new User;
        $token = $userModel->login($userName = $request->param('user_name'), $request->param('password'));
        if ($token === false) {
            return json_response([], STATUS_FAIL, $userModel->getError());
        }
        $newPassword = $request->param('new_password');
        if (!$newPassword) {
            return json_response([], STATUS_INVALD_PARAM, "必须传入新密码");
        }
        $userModel = $userModel->get($userName);
        $userModel->password = md5($userName . $newPassword);
        $userModel->save();
        return json_response([]);
    }
}
